package com.example.androidshixun.fragment;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.androidshixun.ExerciseActivity;
import com.example.androidshixun.R;
import com.example.androidshixun.bean.Exercise;

import java.util.ArrayList;
import java.util.List;

public class ExerciseAdapter extends BaseAdapter implements View.OnClickListener {

    private List<Exercise> exerciseList = new ArrayList<>();
    private Context mContext;

    public ExerciseAdapter(List<Exercise> list, Context ctx) {
        exerciseList = list;
        mContext = ctx;
    }

    @Override
    public int getCount() { return exerciseList == null ? 0 : exerciseList.size(); }

    @Override
    public Object getItem(int position) { return exerciseList.get(position); }

    @Override
    public long getItemId(int position) { return position; }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        List<Object> holder = new ArrayList<>();
        if(convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.exercise_item, null);
            TextView idTv = convertView.findViewById(R.id.id);
            TextView titleTv = convertView.findViewById(R.id.title);
            holder.add(idTv);
            holder.add(titleTv);
            holder.add(new Integer(position));
            convertView.setTag(holder);
            convertView.setOnClickListener(this);
        } else {
            holder = (List<Object>)convertView.getTag();
        }
        ((TextView)holder.get(0)).setText(   String.valueOf(position+1) );
        ((TextView)holder.get(1)).setText(  exerciseList.get(position).title   );
        if(exerciseList.get(position).color == 0) {
            ((TextView)holder.get(0)).setBackgroundResource(R.drawable.exercises_bg_1);
        } else if(exerciseList.get(position).color == 1) {
            ((TextView)holder.get(0)).setBackgroundResource(R.drawable.exercises_bg_2);
        } else if(exerciseList.get(position).color == 2) {
            ((TextView)holder.get(0)).setBackgroundResource(R.drawable.exercises_bg_3);
        } else if(exerciseList.get(position).color == 3) {
            ((TextView)holder.get(0)).setBackgroundResource(R.drawable.exercises_bg_4);
        }
            return convertView;
    }

    @Override
    public void onClick(View v) {
        List<Object> holder = (List<Object>)v.getTag();
        int position = (Integer)holder.get(2);

        Intent intent = new Intent(mContext, ExerciseActivity.class);
        intent.putExtra("TITLE", exerciseList.get(position).title);
        intent.putExtra("URL", exerciseList.get(position).url);
        mContext.startActivity(intent);
    }
}
